package com.znjc.web.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.domain.entity.SysUser;
import com.znjc.common.enums.BusinessType;
import com.znjc.device.domain.DeviceType;
import com.znjc.device.domain.DeviceTypeSerialRef;
import com.znjc.device.domain.IotDataCheckRuleRef;
import com.znjc.device.domain.IotSerial;
import com.znjc.device.service.IDeviceTypeSerialRefService;
import com.znjc.device.service.IDeviceTypeService;
import com.znjc.device.service.IIotSerialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 串口绑定设备类型Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@RestController
@RequestMapping("/device/serialTypeRef")
public class DeviceTypeSerialRefController extends BaseController {
    @Autowired
    private IDeviceTypeSerialRefService deviceTypeSerialRefService;
    @Autowired
    private IDeviceTypeService deviceTypeService;
    @Autowired
    private IIotSerialService iotSerialService;

    /**
     * 根据串口id获取授权设备类型
     */
    @PreAuthorize("@ss.hasPermi('device:serialTypeRef:edit')")
    @GetMapping("/authDeviceType/{serialId}")
    public AjaxResult authDeviceType(@PathVariable("serialId") Long serialId) {
        AjaxResult ajax = AjaxResult.success();
        IotSerial serial = iotSerialService.getById(serialId);
        ajax.put("serial", serial);
        List<DeviceType> deviceTypes = deviceTypeService.list();
        if (CollectionUtils.isNotEmpty(deviceTypes)) {
            List<Long> deviceTypeIds = deviceTypeSerialRefService.getIdList(serialId, 1);
            if (CollectionUtils.isNotEmpty(deviceTypeIds)) {
                deviceTypes.stream().map(d -> {
                    if (deviceTypeIds.contains(d.getId())) {
                        d.setFlag(true);
                    }
                    return d;
                }).collect(Collectors.toList());
            }
            ajax.put("deviceTypes", SysUser.isAdmin(serialId) ? deviceTypes : deviceTypes.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 串口绑定设备类型
     */
    @PreAuthorize("@ss.hasPermi('device:serialTypeRef:edit')")
    @Log(title = "设备类型绑定串口管理", businessType = BusinessType.GRANT)
    @PutMapping("/authDeviceType")
    public AjaxResult insertAuthRole(Long serialId, Long[] deviceTypeIds) {
        if (serialId != null && deviceTypeIds.length == 0) {
            LambdaQueryWrapper<DeviceTypeSerialRef> wrapper = new LambdaQueryWrapper<DeviceTypeSerialRef>();
            wrapper.eq(DeviceTypeSerialRef::getSerialId, serialId);
            deviceTypeSerialRefService.remove(wrapper);
        }
        List<DeviceTypeSerialRef> refList = new ArrayList<DeviceTypeSerialRef>();
        if (serialId != null && deviceTypeIds.length > 0) {
            DeviceTypeSerialRef ref = null;
            for (int i = 0; i < deviceTypeIds.length; i++) {
                ref = new DeviceTypeSerialRef();
                ref.setTypeId(deviceTypeIds[i]);
                ref.setSerialId(serialId);
                refList.add(ref);
            }
        }
        if (CollectionUtils.isNotEmpty(refList)) {
            //先删除
            LambdaQueryWrapper<DeviceTypeSerialRef> wrapper = new LambdaQueryWrapper<DeviceTypeSerialRef>();
            wrapper.eq(DeviceTypeSerialRef::getSerialId, serialId);
            deviceTypeSerialRefService.remove(wrapper);
            //再保存
            deviceTypeSerialRefService.saveBatch(refList);
        }
        return success();
    }

}
